/* 
 * File:   lua03.cpp
 * Author: Vicky.H
 * Email:  eclipser@163.com
 */
#include <iostream>
#include <lua.hpp>      // -llua-5.1
#include <typeinfo>

/*
 * 
 */
int main(void) {
    lua_State* L = lua_open();
    luaL_openlibs(L);
    luaL_dofile(L, "lua03.lua");        // 加载lua脚本
    lua_getglobal(L, "i");               // 将lua中的全局变量i放到栈顶
    
    auto i = lua_tonumber(L, -1);       // 获得lua栈顶的数据，并将其转换换为number
    std::cout << "i :: " << typeid(i).name() << " " << i << std::endl; // d 10
    
    int i2 = lua_tonumber(L, -1);
    std::cout << "i :: " << typeid(i2).name() << " " << i2 << std::endl; // i 10
    
    lua_getglobal(L, "j");
    auto j = lua_tointeger(L, -1);
    std::cout << "j :: " << typeid(j).name() << " " << j << std::endl; // i 10
    
    std::cout << "\n---------------------------" << std::endl;
    
    lua_getglobal(L, "name");
    if (lua_isstring(L, -1)) {
        const char* name = lua_tolstring(L, -1, nullptr);
        std::cout << "name is string" << std::endl;
        std::cout << "name : " << name << std::endl;
    } else {
        std::cout << "name is not string or not found" << std::endl;
    }

    std::cout << "\n---------------------------" << std::endl;
    
    lua_getglobal(L, "tab");
    if (lua_istable(L, lua_gettop(L))) {        // lua_gettop(L) = -1
        std::cout << "tab is table" << std::endl;
    } else {
        std::cout << "tab is not table or not found" << std::endl;
    }
    
    lua_close(L);
    return 0;
}
